package com.tea.room.service.tea.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tea.room.dao.tea.HouseInfoDao;
import com.tea.room.dao.tea.SelectionDao;
import com.tea.room.dao.tea.TeaOrderDao;
import com.tea.room.model.Return;
import com.tea.room.model.tea.HouseInfo;
import com.tea.room.model.tea.Selection;
import com.tea.room.model.tea.TeaOrder;
import com.tea.room.service.tea.TeaOrderService;
import com.tea.room.util.ConstantUtil;
import com.tea.room.util.DateUtils;

@Service
@Transactional
public class TeaOrderServiceImpl implements TeaOrderService {

    @Autowired
    private TeaOrderDao teaOrderDao;
    
    @Autowired
    private SelectionDao selectionDao;
    
    @Autowired
    private HouseInfoDao houseInfoDao;
    
    private static Logger logger = LoggerFactory.getLogger(TeaOrderServiceImpl.class);

    
    @Override
    public Map<String,Object> saveOrder(String roomId, String times, String price, String total) {
    	Map<String,Object> map = new HashMap<String,Object>();
    	
    	logger.info("获取订单号入参         roomId:" + roomId + "---times:" + times 
    			+ "---price:" + price + "---total:" + total);
        if(roomId == null || roomId.equals("")){
            map.put("flag", ConstantUtil.ERROR_FLAG);
            map.put("message", "roomId 为空！");
            return map;
        }
        if(times == null || times.equals("")){
            map.put("flag", ConstantUtil.ERROR_FLAG);
            map.put("message", "times 为空！");
            return map;
        }
        Map<String,Object> map1 = checkTime_interval(roomId, times, total);
        if((boolean) map1.get("flag")){
            map.put("flag", ConstantUtil.ERROR_FLAG);
            map.put("message", "选择时段已被预订,请刷新页面！");
            return map;
        }
        if(total == null || total.equals("")){
            map.put("flag", ConstantUtil.ERROR_FLAG);
            map.put("message", "times 为空！");
            return map;
        }
        if(price == null || price.equals("")){
            map.put("flag", ConstantUtil.ERROR_FLAG);
            map.put("message", "price 为空！");
            return map;
        }
        double d1 = (int)map1.get("length")/2.0;
        Double d2 = Double.valueOf(total);
        if(d1 != d2){
            map.put("flag", ConstantUtil.ERROR_FLAG);
            map.put("message", "total 时长传入有误！");
            return map; 
        }
        HouseInfo houseInfo = new HouseInfo();
        houseInfo.setTeaCode(roomId);
        HouseInfo query = houseInfoDao.query(houseInfo);
        houseInfo.setSales_no(String.valueOf(Integer.valueOf(query.getSales_no()) + 1));
        BigDecimal decimal = new BigDecimal(price);
//        double d3 = Double.valueOf(query.getPrice());
//        double d4 = (d2 - 2) * d3 + 288;
//        if(!"4.5".equals(total) && d4 != decimal.doubleValue()){
//            map.put("flag", ConstantUtil.ERROR_FLAG);
//            map.put("message", "传入金额有误！");
//            return map; 
//        }
        TeaOrder order = new TeaOrder();
        String code = getOrderCode();
        order.setTeaCode(roomId);//茶楼编码
        order.setTime_interval(times);//订单时段
        order.setTotal(total);//累计时长
        order.setPrice(decimal.doubleValue());//订单金额
        order.setSerno(code);//订单编码
    	logger.info("返回订单号         code:" + code );
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date parse = sdf.parse((String) map1.get("reminder"));
            Date start = sdf.parse((String) map1.get("start"));
            order.setStart(start);//到期时间
            order.setReminder(parse);//到期时间
        } catch (ParseException e) {
            e.printStackTrace();
        }
        order.setCrt_date(new Date());
        teaOrderDao.insert(order);
        houseInfoDao.update(houseInfo);
        map.put("order_code", code);
        return map;
    }

    @Override
    public void modifyOrder(TeaOrder o) {
        teaOrderDao.update(o);
    }
    
    @Override
    public void deleteOrder(TeaOrder o) {
        teaOrderDao.delete(o);
    }
    
    /**
     * 生产订单编码
     * @return 订单号
     */
    private String getOrderCode(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String str = sdf.format(new Date());
        return "STL" + str;
    }
    
    /**
     * 检查定时预定时间是否已被预定
     * @param roomId
     * @param times
     * @param total
     * @return
     */
    @Override
    public Map<String,Object> checkTime_interval(String roomId, String times, String total){
        HashMap<String,Object> map = new HashMap<String,Object>();
        map.put("flag", false);
        Selection selection = new Selection();
        String[] split = times.split("-");// 获取订单预定时段
        List<String> list = DateUtils.sortTime(DateUtils.getDateTime(11), DateUtils.getDateTime(12));//获取当前时间往后的时间节点
        int i = list.indexOf("00:00"); //获取零点坐标
        int s = list.indexOf(split[0]); //获取起始坐标
        int e = list.indexOf(split[1]); //获取截止坐标
        map.put("length", e-s);//获取时长
        List<String> today = new ArrayList<String>();// 当天时段
        List<String> tomo = new ArrayList<String>();// 第二天时段
        map.put("start", DateUtils.getToDay(0) + " " + split[0] + ":00");
        map.put("reminder", DateUtils.getToDay(0) + " " + split[1] + ":00");
        /* 当起始时间坐标大于 零点坐标，都为第二天
         * 当截止时间坐标小于零点坐标，都为第一天
         * 一大一小，横跨两天
         */
        if (s > i){
            map.put("start", DateUtils.getToDay(1) + " " + split[0] + ":00");
            map.put("reminder", DateUtils.getToDay(1) + " " + split[1] + ":00");
            tomo.addAll(list.subList(s, e+1));
        } else if (e < i){
            today.addAll(list.subList(s, e+1));
        } else {
            map.put("reminder", DateUtils.getToDay(1) + " " + split[1] + ":00");
            tomo.addAll(list.subList(s, i));
            today.addAll(list.subList(i, e+1));
        }
        //查询当天预定时段
        selection.setTeaCode(roomId);
        selection.setSame_day(DateUtils.getToDay(0));
        selection.setCrt_date(new Date());
        Selection s1 = selectionDao.query(selection);
        String old = "";
        if(s1 != null){
            old = s1.getSelection();
            for (int j = 0; j < today.size(); j++) {
                int indexOf = old.indexOf(today.get(j));
                if(indexOf != -1){
                    map.put("flag", true);
                }
            }
        }
        //查询第二天预定时段
        if(tomo.size() > 0){
            map.put("reminder", DateUtils.getToDay(1) + " " + split[1] + ":00");
            selection.setSame_day(DateUtils.afterday(new Date()));
            Selection s2 = selectionDao.query(selection);
            if(s2 != null){
                old = s2.getSelection();
                for (int j = 0; j < tomo.size(); j++) {
                    int indexOf = old.indexOf(tomo.get(j));
                    if(indexOf != -1){
                        map.put("flag", true);
                    }
                }
            }
        }
        return map;
    }

    @Override
    public List<TeaOrder> findOrder() {
        List<TeaOrder> list = teaOrderDao.queryOrder();
        return list;
    }

    @Override
    public List<TeaOrder> findStartOrder() {
        List<TeaOrder> list = teaOrderDao.querySatrtOrder();
        return list;
    }

    @Override
    public Return queryOrderByLimit(HttpServletRequest request) {
        Return rn = new Return();
        Map<String, Object> map = null;
        
        List<TeaOrder> list = teaOrderDao.queryOrderByLimit(map);
        
        return rn;
    }
    

}
